package br.com.dataphonebr;

import br.com.dataphonebr.entity.Grupo;
import br.com.dataphonebr.service.GrupoService;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

public class AppointmentGroupActivity extends GenericActivity<Grupo>{
	
	private EditText name;
	private EditText description;
	private CheckBox sendSms;
	private GrupoService grupoService;
	
	public AppointmentGroupActivity() {
		super(Grupo.class);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appointment_group);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		this.init();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.appointment, menu);
	    return true;
	} 	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	    case R.id.saveAppointmentMenu:
	    	saveOrUpdate(item.getActionView());
	        return true;
	    case R.id.cancelAppointmentMenu:
			openView(AppointmentGroupActivity.this, AppointmentGroupListActivity.class, true);
			return true;
	    case android.R.id.home:
			openView(AppointmentGroupActivity.this, AppointmentGroupListActivity.class, true);
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void init() {
		grupoService = new GrupoService(this);
		setServiceInstance(grupoService);
		super.init();
	}
	
	@Override
	public Grupo loadInstance(){
		Grupo grupo = super.loadInstance();
		name.setText(grupo.getNome());
		description.setText(grupo.getDescricao());
		sendSms.setChecked(grupo.getEnviaSMS());
		return grupo;
	}
	
	@Override
	public void afterPersist() {
		openView(AppointmentGroupActivity.this, AppointmentGroupListActivity.class, true);
		super.afterPersist();
	}
	
	@Override
	public void afterUpdate() {
		openView(AppointmentGroupActivity.this, AppointmentGroupListActivity.class, true);
		super.afterUpdate();
	}
	
	public void cancel(View v){
		openView(AppointmentGroupActivity.this, AppointmentGroupListActivity.class, true);
	}
	
	public void prepareComponents() {
		name = (EditText)findViewById(R.id.nameGroupTxt);
		description = (EditText)findViewById(R.id.descriptionGroupTxt);
		sendSms = (CheckBox)findViewById(R.id.sendSmsChk);
	}

	public void prepareToPersist(){
		if (getId() != null && getId() > 0)
			getInstance().setCodigo(getId());
		else
			getInstance().setCodigo(null);
		getInstance().setNome(name.getText().toString());
		getInstance().setDescricao(description.getText().toString());
		getInstance().setEnviaSMS(sendSms.isChecked());
	}
	
	@Override
	public void prepareToUpdate() {
		prepareToPersist();
	}

}